package cn.itcast.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author syf
 * @version 1.0
 * @date 2019/07/25 17:20
 * @Description TODO:调用者的控制器
 */
@RestController
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "defaultFallBack") //默认的Fallback
public class ConsumerController {

    @Autowired
    //远程访问userservice服务接口
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallBack")//服务降级
    public String queryById(@PathVariable(name = "id") Long id){

        //服务发现
//        //根据服务id（spring.application.name)服务实例列表
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        //取出一个服务实例
//        ServiceInstance instance = instances.get(0);
//        //从实例中获取host和port，组成url
//        String url=String.format("http://%S:%s/user/%s",instance.getHost(),instance.getPort(),id);



        //负载均衡
       String url="http://user-service/user/"+id;
        //查询
        String user = restTemplate.getForObject(url, String.class);
        return user;
    }

    public String queryByIdFallBack(Long id){

        return "网络太拥挤，请稍等";
    }

}
